package com.sky.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Component;

import java.util.Set;

@Aspect
@Component
@Slf4j
public class CacheSyncAspect {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 切入点
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.CacheSync)")
    public void cacheRefreshPointCut() {
    }

    private static final String ALL_CACHE ="*dish_*";

    /**
     * 前置通知
     *
     * @param joinPoint
     */
    @Before("cacheRefreshPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始刷新缓存..");

        try {
            // 删除所有缓存数据
            RedisConnection connection = redisConnectionFactory.getConnection();
            Set<byte[]> keys = connection.keys(ALL_CACHE.getBytes());
            connection.del(keys.toArray(new byte[keys.size()][]));
        } catch (Exception e) {
            log.info("缓存刷新失败，异常忽略...");
        }

    }
}
